<template>
  <div class="mymissions-container">
    <v-layout wrap justify-center align-center>
      <!-- <v-flex class="overview-wrapper">
        <div class="budget">
          <span>Budget:</span>
          <span>$ {{ balance }}</span>
        </div>
        <div class="order">
          <span>Order:</span>
          <span>{{ orderCount }}</span>
        </div>
      </v-flex>-->

      <v-flex md12 xs12 class="overflow-tab mb-3">
        <v-tabs
          v-model="tab"
          class="pos-abs"
          fixed-tabs
          color="transparent"
          slot="extension"
          @change="onTabClicked"
        >
          <v-tabs-slider color="primary"></v-tabs-slider>
          <v-tab
            v-for="(item, index) in tabItems"
            :key="index"
            :href="`#${item.value}`"
            class="primary--text"
          >
            <span class="title">{{ item.text }}</span>
          </v-tab>
        </v-tabs>
      </v-flex>

      <v-flex md12 xs12>
        <ul class="tab-panel-list">
          <li class="tab-panel-li card" v-for="(mission, i) in missionList">
            <v-layout row wrap justify-start>
              <v-flex md3 class="image-wrapper">
                <img :src="mission.productImg" alt />
              </v-flex>
              <v-flex md9 wrap justify-start>
                <v-layout row wrap>
                  <v-flex
                    md8
                    class="item-name title ellipsis"
                    @click="onMissionDetail(mission)"
                  >{{ mission.titleEnglish }}</v-flex>
                  <v-flex md12>
                    <v-layout wrap>
                      <v-flex md7 text-md-left>
                        <span class="real-price">$ 0.00</span>
                        <span class="ml-2 original-price" d-inline-block>$ {{ mission.price }}</span>
                      </v-flex>
                      <v-flex md7 text-md-left>
                        <span class="real-price">Refund:</span>
                        <span
                          class="real-price"
                        >{{ mission.commission ? mission.commission.toFixed(2) : ''}}</span>
                      </v-flex>
                    </v-layout>
                  </v-flex>
                  <v-flex md12 text-md-left py-2>
                    <v-btn
                      color="red"
                      dark
                      v-if="mission.orderStatus === 1"
                      @click="onCancelMission(mission.label, mission)"
                    >
                      <span>Cancel</span>
                    </v-btn>
                    <v-btn
                      color="cyan darken-1"
                      dark
                      @click="onOrderUpload(mission.label, mission)"
                      v-if="mission.orderStatus === 1"
                    >
                      <span>Order Upload</span>
                    </v-btn>

                    <v-btn
                      color="primary"
                      dark
                      @click="onReviewUpload(mission.label, mission)"
                      v-if="mission.orderStatus === 4 && mission.taskType !== 1"
                    >
                      <span>Review Upload</span>
                    </v-btn>
                  </v-flex>
                </v-layout>
              </v-flex>
            </v-layout>
          </li>
        </ul>
      </v-flex>
    </v-layout>
    <v-dialog v-model="modal" max-width="290">
      <v-card>
        <v-card-title class="headline">{{ modalTitle }}</v-card-title>

        <v-card-text>{{ modalText }}</v-card-text>

        <v-card-actions>
          <v-spacer></v-spacer>

          <v-btn color="grey darken-1" flat text @click="modal = false">Cancel</v-btn>

          <v-btn color="blue darken-1" flat text @click="onModalConfirm">Confirm</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <v-dialog v-model="dialog" max-width="720">
      <v-card>
        <v-card-title class="headline">Upload</v-card-title>

        <v-card-text>
          <div class="input-wrapper" v-if="dialogItem.orderStatus === 1">
            <input ref="orderInput" type="file" accept="image/*" @change="onOrderFileChange" />
            <img class="preview-image" :src="orderImagePreview" alt v-if="orderImagePreview !== ''" />

            <v-icon v-if="orderImagePreview === ''">cloud_upload</v-icon>

            <div v-if="orderImagePreview === ''" class="upload-tip title-color">Choose order image</div>
          </div>

          <div class="input-wrapper" v-if="dialogItem.orderStatus === 4">
            <input ref="reviewInput" type="file" accept="image/*" @change="onReviewFileChange" />
            <img
              class="preview-image"
              :src="reviewImagePreview"
              alt
              v-if="reviewImagePreview !== ''"
            />

            <v-icon v-if="reviewImagePreview === ''">cloud_upload</v-icon>

            <div v-if="reviewImagePreview === ''" class="upload-tip title-color">Choose review image</div>
          </div>
        </v-card-text>

        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="grey darken-1" flat text @click="dialog = false">Cancel</v-btn>
          <v-btn color="blue darken-1" flat text @click="onDialogConfirm">Confirm</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>


<script lang="ts">
// 使用类装饰器
import { Component, Vue } from "vue-property-decorator";
import { Api, Login, FileHandler } from "@/api";
import { forEach } from "lodash";
import { KV } from "@/utils/type";
import { PageOptions, TopupStatusKV } from "@/utils/constants";
import { ReqProfitIncome, ReqTaskInfo, RespFileVo } from "@/api/bean";
import { getTime } from "@/utils/commonUtils";
import Cookie from 'js-cookie';
declare const $Vue: Vue;

@Component
export default class Missions extends Vue {

  private tabItems: any = [
    {
      text: "New Order",
      value: '1'
    },
    {
      text: "In Process",
      value: '2',
    },
    {
      text: "Orders 100 Days",
      value: '3',
    },
  ];

  private tab: any = '1';

  private queryForm: any = {

  };

  private selectedTab: string = "New Order";
  private dialog: boolean = false;
  private dialogItem: any = {};
  private get orderCount() {
    return 0;
  }
  private balance: number = 0;

  private orderImagePreview: string = "";
  private reviewImagePreview: string = "";

  private orderImage: any = null;
  private reviewImage: any = null;

  private modalItem: any = {};
  private modalTitle: any = 'Attention!';
  private modalText: any = '';
  private modal: any = false;

  private orderImageUrl: string = "";
  private reviewImageUrl: string = "";

  private dialogType: number = 1;

  private loading: boolean = false;
  private isQuery: boolean = false;

  private pagination: any = {
    pageCount: 20,
    page: 1,
    limit: 10,
    offset: 0
  };

  private missionList: Array<any> = [];

  private missionListAll: Array<any> = [];

  private getTime(date: string) {
    return getTime(date);
  }

  protected mounted() {
    this.getData();
    $Vue.$emit("title", { message: 'MyMissions' });
    this.tab = '1';
  }

  private getData() {
    this.getMyMissionList("newOrder");
    this.getMyMissionList("inProcess");
    this.getMyMissionList("100days");
  }

  private onTabClicked(value: any) {
    this.missionList = this.missionListAll[Number(value) - 1];
  }

  private onQuery(from?: string) {
    let params: any = {};

    let valid = 0;
    forEach(this.queryForm, (item, key) => {
      item ? (params[key] = item) : valid++;
    });
    if (valid === 3) {
      return $Vue.$emit("snackbar", {
        message: "请至少填写一个查询条件"
      });
    }

    if (from === undefined) {
      this.pagination.offset = 0;
      this.pagination.page = 1;
    }

    if (this.queryForm.beginTime && this.queryForm.endTime) {
      if (
        new Date(this.queryForm.beginTime).getTime() >
        new Date(this.queryForm.endTime).getTime()
      ) {
        return $Vue.$emit("snackbar", {
          text: "起始日期不能早于结束日期"
        });
      }
      params.endTime = new Date(this.queryForm.endTime + " 23:59:59").getTime();
      params.beginTime = new Date(
        this.queryForm.beginTime + " 00:00:00"
      ).getTime();
    } else if (this.queryForm.beginTime || this.queryForm.endTime) {
      return $Vue.$emit("snackbar", {
        text: "请选择完整起止日期"
      });
    }
    params.limit = this.pagination.limit;
    params.offset = this.pagination.offset;
    this.isQuery = true;
    // this.getMissionList(params);
  }

  private onPageChange(value: any) {
    let limit = this.pagination.limit;
    this.pagination.offset = (value - 1) * limit;
    if (!this.isQuery) {
      this.getData();
    } else {
      this.onQuery("wyvonj");
    }
  }

  private onMissionDetail(data: any) {
    this.$router.push({
      name: "MissionDetail",
      params: data
    });
    sessionStorage.setItem("MissionDetail", JSON.stringify(data));
  }
  /**
   * 提交订单
   */
  private onOrderUpload(label: string, mission: any) {
    this.dialog = true;
    this.dialogItem = mission;
    this.dialogType = 1;
  }

  /**
   * 提交评价
   */
  private onReviewUpload(label: string, mission: any) {
    this.dialog = true;
    this.dialogItem = mission;
    this.dialogType = 2;
  }

  private onOrderFileChange(ev: any) {
    let file = ev.target.files[0];
    this.orderImage = file;
    this.handleImageFile(file, "order");
  }

  private onReviewFileChange(ev: any) {
    let file = ev.target.files[0];
    this.reviewImage = file;
    this.handleImageFile(file, "review");
  }

  private handleImageFile(file: File, type: string) {
    const reader = new FileReader();
    // 使用base64上传
    reader.onload = (ev: any) => {
      if (type === "order") {
        this.orderImagePreview = ev.target.result;
      } else {
        this.reviewImagePreview = ev.target.result;
      }
    };
    reader.readAsDataURL(file);
  }
  /**
 * 处理任务列表显示
 */
  private handleMissionList(list: Array<any>) {
    let list1: Array<any> = [];
    let list2: Array<any> = [];
    let list3: Array<any> = [];
    list.forEach((item: any) => {
      let orderImg = null;
      item.orderImgArr = [];
      if (item.orderImg) {
        if (item.orderImg.match(/\[/g)) {
          try {
            orderImg = JSON.parse(item.orderImg);
            item.orderImgArr = orderImg;
          } catch (err) {
            item.orderImgArr = [item.orderImg];
            console.error(err);
          }
        } else {
          item.orderImgArr = [item.orderImg];
        }
      }

      // 新订单
      if (item.orderStatus === 1) {
        list1.push(item);
      }
      // 正在进行中
      if (item.orderStatus >= 3 && item.orderStatus <= 5) {
        list2.push(item);
      }
      // 已完成
      if (item.orderStatus >= 6 || item.orderStatus === -1) {
        list3.push(item);
      }
    });

    this.missionListAll = [list1, list2, list3];
  }

  private onDialogConfirm() {
    if (this.dialogType === 1) {
      this.uploadFile(this.orderImage, "order");
    } else if (this.dialogType === 2) {
      this.uploadFile(this.reviewImage, "review");
    }
  }


  private onDialogCancel() {
    this.dialog = false;
    this.orderImagePreview = "";
    this.orderImage = null;
    this.reviewImagePreview = "";
    this.reviewImage = null;
  }

  private handleFileUploaded(data: RespFileVo, type: string) {
    if (type === "order") {
      this.orderImageUrl = data.fileUrl;
      this.placeOrder(data.fileUrl);
    } else {
      this.reviewImageUrl = data.fileUrl;
      this.saveReview(data.fileUrl, this.dialogItem.orderImg);
    }
  }

  private onCancelMission(label: string, mission: any) {
    this.modalItem = mission;
    this.modal = true;
    this.modalText = 'Confirm to cancel order?';

  }

  private onModalConfirm() {
    this.cancelMyMission();
  }

  /**
    * 保存文件
    */
  private async uploadFile(file: File, type: string) {
    const params: FormData = new FormData();
    params.append("file", file);
    const { data } = await FileHandler.uploadFile.r(params);
    console.log("uploadFile", data);
    if (data.result === 0) {
      this.handleFileUploaded(data.data[0], type);
    } else {
    }
  }

  /**
   * 下订单 卖家上传订单截图
   */
  private async placeOrder(img: string) {
    const params: any = {
      orderId: this.dialogItem.orderId,
      orderNumber: this.dialogItem.orderNumber,
      img: JSON.stringify([img])
    };
    const { data } = await Api.placeOrder.r(params);
    console.log("placeOrder", data);
    this.getData();
    if (data.result === 0) {
      // this.saveReview(this.reviewImageUrl);
      $Vue.$emit("snackbar", {
        message: data.message
      });
      // this.getMyMissionList();
    } else {
    }
  }

  /**
   * 保存评价 买家上传评价截图
   */
  private async saveReview(img: string, orderImg: string) {
    let orderImgArr = [];

    if (orderImg) {
      orderImgArr = JSON.parse(orderImg);
    }

    let imgArr: any = Array.isArray(img) ? img : [img, orderImgArr[0]];
    const params: any = {
      orderId: this.dialogItem.orderId,
      orderNumber: this.dialogItem.orderNumber,
      img: JSON.stringify(imgArr)
    };
    const { data } = await Api.saveReview.r(params);
    console.log("saveReview", data);
    if (data.result === 0) {
      $Vue.$emit("snackbar", {
        message: "Successfully uploaded"
      });
      // this.getMyMissionList();
      this.getData();
    } else {
      $Vue.$emit("snackbar", {
        message: data.message
      });
    }
  }

  /**
   * 获取我的任务列表
   */
  private async getMyMissionList(type: string) {
    let params: any = {
      limit: 1000,
      offset: 0,
      buyerUserId: Number(Cookie.get('p_userId'))
    };
    let orderStatusArr = [];
    if (type === "newOrder") {
      params.orderStatusArr = [1];
    }
    if (type === "inProcess") {
      params.orderStatusArr = [3, 4, 5];
    }
    if (type === "100days") {
      params.endTime = new Date().getTime();
      params.beginTime = new Date().getTime() - 100 * 24 * 60 * 60 * 1000;
      params.orderStatusArr = [-1, 6];
    }
    this.dialog = false;
    const { data } = await Api.getOrderList.r(params);
    console.log("getOrderList", data);
    if (data.result === 0) {
      // this.orderCount = data.data.totalCount;
      // this.handleMissionList(data.data.dataList);
      let list: any = data.data.dataList;
      list.forEach((item: any) => {
        let orderImg = null;
        item.orderImgArr = [];
        if (item.orderImg) {
          if (item.orderImg.match(/\[/g)) {
            try {
              orderImg = JSON.parse(item.orderImg);
              item.orderImgArr = orderImg;
            } catch (err) {
              item.orderImgArr = [item.orderImg];
            }
          } else {
            item.orderImgArr = [item.orderImg];
          }
        }
      });
      if (type === "newOrder") {
        this.missionListAll[0] = list;
      }
      if (type === "inProcess") {
        this.missionListAll[1] = list;
      }
      if (type === "100days") {
        this.missionListAll[2] = list;
      }
      this.missionList = this.missionListAll[Number(this.tab) - 1];
    } else {
      $Vue.$emit("snackbar", {
        message: data.message
      });
    }

  }

  /**
   * 取消已有订单
   */
  private async cancelMyMission() {
    const params: any = {
      orderId: this.modalItem.orderId
    };
    const { data } = await Api.invalidOrder.r(params);
    console.log("invalidOrder", data);
    $Vue.$emit("snackbar", {
      message: data.message
    });
    if (data.result === 0) {
      this.getData();
    } else {
    }
  }

  private async getUserInfo() {
    const params: any = {
      userId: Cookie.get('p_userId')
    };
    const { data } = await Login.getUserBalance.r();
    console.log("getSingleUserInfo", data);
    if (data.result === 0) {
      // this.balance = data.data;
    } else {
      $Vue.$emit("snackbar", {
        message: data.message
      });
    }
  }

}
</script>

<style lang="less" scoped>
@import url(../../styles/variables.less);
.mymissions-container {
  width: 100%;
  height: 100%;
  position: relative;
  .overview-wrapper {
    height: 2rem;
    width: 100%;
    color: white;
    background-color: @primary;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 1.2rem;
    box-sizing: border-box;
  }
  .tab-panel-list {
    width: 100%;
    padding: 2px 0.4rem;
    box-sizing: border-box;
    .tab-panel-li {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0.6rem 0.3rem;
      margin-bottom: 0.2rem;
      border: 0.8px solid #efefef;
      border-radius: 8px;
      margin-bottom: 0.4rem;
      .image-wrapper {
        flex-basis: 20%;
        width: 20%;
        img {
          max-width: 8rem;
          max-height: 8rem;
        }
      }
      // Lft@2017514
      .info-wrapper {
        flex-basis: 80%;
        width: 80%;
        display: flex;
        flex-direction: column;
        padding-left: 8px;
        box-sizing: border-box;
        .item-name {
          width: 84%;
          font-size: 1.1rem;
          height: 1.2rem;
          line-height: 1.2rem;
          text-align: left;
        }
      }
      .item-profit {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        padding: 4px 0;
      }
      .item-actions {
        display: flex;
        justify-content: flex-end;
        .cube-btn {
          width: auto;
          height: 1.5rem;
          padding: 1px 6px;
          font-size: 0.9rem;
          margin-right: 6px;
        }
      }
    }
  }

  .scroll-view {
    height: calc(100% - 6rem);
    overflow-x: hidden;
    overflow-y: auto;
  }

  .dialog-wrapper {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    background: rgba(0, 0, 0, 0.2);
    z-index: 1;
    .upload-wrapper {
      position: relative;
      width: 80%;
      height: 80%;
      background: white;
      border-radius: 1rem;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      padding: 1rem;
      box-sizing: border-box;
      .close-wrapper {
        text-align: right;
        width: 100%;
        .icon {
          color: #f44336;
        }
      }
      .input-wrapper {
        position: relative;
        width: 90%;
        height: 80%;
        border: 1px dashed #ddd;
        display: flex;
        justify-content: center;
        align-items: center;
        margin: 1rem;
        border-radius: 1rem;
        flex-direction: column;
        .preview-image {
          width: 90%;
        }
        .icon {
          color: #888;
          font-size: 2rem;
        }
        input {
          position: absolute;
          width: 100%;
          height: 100%;
          top: 0;
          left: 0;
          opacity: 0;
        }
        div {
          margin-top: 1.2rem;
        }
      }
    }

    .dialog-actions {
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      > div {
        flex-basis: 50%;
        width: 50%;
        height: 2rem;
        line-height: 2rem;
      }

      .confirm {
        color: #fa991a;
      }
    }
  }
}

.list {
  width: 375px;
  max-width: 100%;
  height: 100%;
  margin: 0 auto;
  padding: 0;
  border: 1px solid #ddd;
  list-style-type: none;
  text-align: center;
  .item {
    display: flex;
    padding: 10px 0;
    width: 100%;
    text-align: left;
  }
  .avatar {
    border-radius: 50%;
    margin-left: 15px;
    margin-right: 6px;
    min-width: 48px;
    width: 48px;
    height: 48px;
    background-size: cover;
    outline: none;
  }
  p {
    margin: 0;
    word-wrap: break-word;
    font-size: 14px;
  }
  .bubble {
    padding: 7px 10px;
    color: #333;
    background: #fff;
    box-shadow: 0 3px 2px rgba(0, 0, 0, 0.1);
    position: relative;
    max-width: 420px;
    min-width: 80px;
    margin: 0 20px 0 5px;
  }
  &:before {
    content: "";
    border-style: solid;
    border-width: 0 10px 10px 0;
    position: absolute;
    top: 0;
    left: -10px;
  }
  .meta {
    font-size: 0.8rem;
    color: #999;
    margin-top: 3px;
  }
}

.input-wrapper {
  position: relative;
  width: 90%;
  height: 80%;
  border: 1px dashed #ddd;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 1rem;
  border-radius: 1rem;
  flex-direction: column;
  .preview-image {
    width: 90%;
  }
  .icon {
    color: #888;
    font-size: 2rem;
  }
  input {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    opacity: 0;
  }
  div {
    margin-top: 1.2rem;
  }
}

input {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
}
</style>


